// 1.获取图书并展示
function renderBooks(){
    // 发送Ajax请求，获取图书
    axios({
        method:'GET',
        url:'http://www.itcbc.com:3006/api/getbooks',
        params:{
            appkey:'xiaoliang1'
        }
    }).then(({data:res})=>{
        // 渲染到表格中
        const arr = res.data.map(item => {
            return `
                <tr>
                    <th scope="row">${item.id}</th>
                    <td>${item.bookname}</td>
                    <td>${item.author}</td>
                    <td>${item.publisher}</td>
                    <td>
                    <button data-id="${item.id}" type="button" class="btn btn-link btn-sm btn-delete">删除</button>
                    <button type="button" class="btn btn-link btn-sm btn-update">编辑</button>
                    </td>
                </tr>
            `
        })
        document.querySelector('tbody').innerHTML = arr.join('');
    })
}
renderBooks()


// 2.添加图书
// 模态框语法：const myModal = new bootstrap.Modal(盒子)
const myModal = new bootstrap.Modal(document.querySelector('#addModal'))
// myModal.show()//让模态框显示
// myModal.hide()//让模态框隐藏

document.querySelector('#add-btn').addEventListener('click',function(){
   
    myModal.show();
})
// 点击模态框中的确认按钮，完成添加
document.querySelector('#addBtn').addEventListener('click',function(){
    // 最终目的，就是把输入框的值，提供给接口
    let bookname = document.querySelector('#addForm [name="bookname"]').value;
    let author = document.querySelector('#addForm [name="author"]').value;
    let publisher = document.querySelector('#addForm [name="publisher"]').value;
    // console.log(bookname,author,publisher);
    axios({
        method:'POST',
        url:'http://www.itcbc.com:3006/api/addbook',
        data:{
            bookname:bookname,
            author:author,
            publisher:publisher,
            appkey:'xiaoliang1'
        }
    }).then(({data:res}) => {
        // 添加成功
        myModal.hide();//关闭模态框
        renderBooks();;//重新获取全部图书，重新渲染
    })
})
 

// 3.删除图书
document.querySelector('tbody').addEventListener('click',function(e){
    if(e.target.classList.contains('btn-delete')) {
        let id = e.target.dataset.id;
        axios({
            method:'DELETE',
            url:'http://www.itcbc.com:3006/api/delbook',
            params:{
                id:id,
                appkey:'xiaoliang1'
            }
        }).then(({data:res}) => {
            renderBooks();
        })
    }
})
// 4.修改图书